package com.sumainfor.pc.market.service;

import com.qiniu.util.Json;
import com.sumainfor.common.Constants;
import com.sumainfor.common.util.*;
import com.sumainfor.common.utlis.ComUtils;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.pc.market.dao.RdHciMapper;
import com.sumainfor.pc.market.dao.RdHousingConInfoMapper;
import com.sumainfor.pc.market.dao.RdHousingConMapper;
import com.sumainfor.pc.market.dao.UtilsMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Date 2018年11月7日
 * @Describe 房源详表配置
 */
@Service
public class RdHousingConService implements Serializable {

    private ReentrantLock lock = new ReentrantLock(false);

    Logger log = LoggerFactory.getLogger(RdHousingConService.class);// 日志

    @Autowired
    private RdHousingConMapper rdHousingConMapper;
    @Autowired
    private RdHousingConInfoMapper rdHousingConInfoMapper;
    @Autowired
    private RdHciMapper rdHciMapper;
    @Autowired
    private UtilsMapper utilsMapper;
    /**
     *运营部服务管家变更房源配置根据房源主表编号查询各个房间的房源的配置
     */
    public List<Map<String,Object>> getHouConAllList(Map<String,Object> params){
        return rdHousingConMapper.getHouConAllList(params);
    }
    /**
     * 工程部验房的时候 新增房源配置
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult addHouCon(Map<String, Object> params) {
        JsonResult result=new JsonResult();
        /**
         * 加锁操作
         */
        lock.lock();
        try{
            try {
                //房源配置详表编号
        /*        String UUID="";
                Map<String,Object> uuid=utilsMapper.getUUID(new HashMap<String,Object>(){{
                    put("uuid", "HouConId");
                    put("database", Constants.DATA_SOURCE_TCMKT);
                    put("surface", "tcmkt_housing_con_info");
                }});
                if(uuid!=null){
                    int number=Integer.valueOf(uuid.get("uuid").toString());
                    UUID= ComUtils.getLocalTrmSeqNum("con",number);
                }else{
                    UUID=ComUtils.getLocalTrmSeqNum("con",0);
                }*/
                //房源网络电视配置编号
         /*       String UUID2="";
                Map<String,Object> uuid2=utilsMapper.getUUID(new HashMap<String,Object>(){{
                    put("uuid", "HouConInId");
                    put("database", Constants.DATA_SOURCE_TCMKT);
                    put("surface", "tcmkt_housing_con_internet");
                }});
                if(uuid2!=null){
                    int number=Integer.valueOf(uuid2.get("uuid").toString());
                    UUID2= ComUtils.getLocalTrmSeqNum("hin",number);
                }else{
                    UUID2=ComUtils.getLocalTrmSeqNum("hin",0);
                }*/
                //组装新增参数
                Map<String,Object> map=new HashMap<String,Object>();
                map.put("by", ContextUtils.getUserId());//操作人
                map.put("term", "4");// 更新端 Update端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                map.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonInsertParms(map);
                //验证数据的数量
                int num=0;
//                int num1=0;
                int num2=0;
//                int lnum1=0;
                //房源配置列表
                List<Map<String,Object>> houList=(List<Map<String, Object>>)params.get("houList");
                for (Map<String,Object> houMap:houList){
                    houMap.putAll(map);
                    //新增房源配置主表
                    num=num+rdHousingConMapper.addRdHouCon(houMap);
//                    List<Map<String,Object>> conList=(List<Map<String,Object>>)houMap.get("conList");
//                    lnum1=lnum1+conList.size();
            /*        for (Map<String,Object> conMap:conList) {
                        conMap.putAll(map);
                        //新增房源配置详表
                        conMap.put("HouConId",UUID+num1);//房源配置详表编号
                        num1=num1+rdHousingConInfoMapper.addRdHouConInfo(conMap);
                    }*/
                }
                //网络和电视
             /*   List<Map<String,Object>> netWorkList=(List<Map<String,Object>>)params.get("netWorkList");
                for (Map<String,Object> netWorkMap:netWorkList){
                    netWorkMap.putAll(map);
                    netWorkMap.put("HouConInId",UUID2+num2);
                    num2=num2+rdHciMapper.addRdHci(netWorkMap);
                }*/
                System.out.println("num="+num);
                System.out.println("houList.size()="+houList.size());
//                System.out.println("num1="+num1);
//                System.out.println("lnum1="+lnum1);
                System.out.println("num2="+num2);
//                System.out.println("netWorkList.size()="+netWorkList.size());
                if (num==houList.size() ){
                    result.putSuccess("操作成功");
                }else{
                    result.putFailed("服务器繁忙");
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                }
            } catch (Exception e) {
                result.putFailed("服务器繁忙");
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

            }
        }
        finally {
            lock.unlock();
        }
        return result;
    }
    /**
     * 租客端协助开门查询房源的房间配置
     */
    public JsonResult getRdInteHouConInfoList(Map<String,Object> params){
        JsonResult result=new JsonResult();
        if (params.get("HouConId")==null || params.get("HouId")==null){
            return result.putFailed("参数不正确");
        }
        List<Map<String,Object>> list=rdHousingConMapper.getRdInteHouConInfoList(params);
        System.out.println("list:"+list);
        if (list==null){
            list=new ArrayList<Map<String,Object>>();
        }
        return result.put(list);
    }
    /**
     * 获取房间钥匙
     */
    public JsonResult getRdIntePassWord(Map<String,Object> params){
        //判断当前时间是否在08:30---20:00
        String format = "HH:mm:ss";
        SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss");
        String now = sf.format(new Date());
        Boolean iFBill=false;//是否需要账单
        try {
            Date nowTime = new SimpleDateFormat(format).parse(now);
            Date startTime = sf.parse("09:00:00");
            Date endTime = sf.parse("17:00:00");
            iFBill=DateUtils.isEffectiveDate(nowTime,startTime,endTime);
        } catch (java.text.ParseException e) {
            log.debug("时间转换错误");
        }
        System.out.println("是否需要账单:"+iFBill);
        JsonResult result=new JsonResult();
        if (params.get("HouConId")==null || params.get("HouId")==null ||params.get("checktype")==null){
            return result.putFailed("参数不正确");
        }

        List<Map<String,Object>> IdentifierList=rdHousingConMapper.getRdInteHouConInfoList(params);
        if (IdentifierList==null){
            log.debug("缺少智能设备编号:IdentifierList");
            return result.putFailed("服务器繁忙");
        }
        int num=0;
        int num2=0;//科技侠
        for (Map<String,Object> InteMap:IdentifierList){
            //0.蜂电   1.大华   2.科技侠   3.果加
            if (InteMap.get("Intelligent").toString().equals("2")){
                num2++;
                params.put("clientId", InteDeviceLockConfig.CLIENT_ID);//应用编号
                params.put("accessToken",InteDeviceLockConfig.ACCESS_TOKEN);//访问令牌
                params.put("lockId",InteMap.get("Identifier"));//智能设备编号
                params.put("keyboardPwdVersion","4");//键盘密码版本, 三代锁的密码版本为4
                params.put("keyboardPwdType","1");//参数值 单次	1
                //密码有效时间
                //获取当前时间
                params.put("startDate", InteDeviceLockUtil.getTimeSign(InteDeviceLockUtil.getTimeAfter(System.currentTimeMillis(),0,"yyyy-MM-dd HH:mm:ss"),"yyyy-MM-dd HH:mm:ss"));
                //获取一个小时之后的时间
                params.put("endDate",InteDeviceLockUtil.getTimeSign(InteDeviceLockUtil.getTimeAfter(System.currentTimeMillis(),60*60*1000,"yyyy-MM-dd HH:mm:ss"),"yyyy-MM-dd HH:mm:ss"));
                params.put("date",InteDeviceLockUtil.getTimeSign());
                System.out.println("params:"+params);
                Map<String,Object> map=InteDeviceLockUtil.keyboardPwdGet(params);
                if (map.get("keyboardPwd")!=null){
                    InteMap.putAll(map);
                    num++;
                }else{
                    return result.putFailed("服务器繁忙");
                }
                InteMap.putAll(map);
            }
        }
        //判断是系统还是租客
        if (params.get("checktype").toString().equals("2")){
            if (num==num2){
                result.put(IdentifierList);
            }else{
                result.putFailed("服务器繁忙");
            }
        }
        return result;
    }
}
